import 'dart:isolate';

import 'package:flutter_foreground_task/flutter_foreground_task.dart';
import 'package:novel_reader/apk.dart';
import 'package:shared_preferences/shared_preferences.dart';

bool ttsReady = false;

@pragma('vm:entry-point')
void startCallback() {
  FlutterForegroundTask.setTaskHandler(ReadNovelHandler());
  //test FlutterIsolate
  
}

class ReadNovelHandler extends TaskHandler {
  ReadNovelHandler();

  List<String> spkList = List<String>.empty();

  @override
  void onDestroy(DateTime timestamp, SendPort? sendPort) {
    // TODO: implement onDestroy
    //print('fhz:destroy service');
    
    if (speaking) {
      ttsPause = true;
      flutterTts.stop();
    }
    //FlutterForegroundTask.setOnLockScreenVisibility(false);
    //bgTask?.kill();
  }

  @override
  void onRepeatEvent(DateTime timestamp, SendPort? sendPort) {
    // TODO: implement onRepeatEvent
    //print('fhz: repeat ${timestamp.toString()}');
    //FlutterForegroundTask.wakeUpScreen();
  }

  Future<void> startSpeakTask(SendPort? sendPort) async {
    final prefs = await SharedPreferences.getInstance()
      ..reload();
    spkList = prefs.getStringList('spkList')!;
    ttsStart = prefs.getInt('ttsStart')!;
    speed = prefs.getDouble('speed')!;

    //print('fhz: start service : ${spkList.length}');
    if (spkList.isEmpty) {
      print('fhz:list is empty');
      FlutterForegroundTask.stopService();
      return;
    }
    //print('fhz:start speak');
    if (!ttsReady) {
      await ttsInit();
      ttsReady = true;
      speakList(spkList, sendPort);
    } else {
      speakList(spkList, sendPort);
    }
  }

  @override
  void onStart(DateTime timestamp, SendPort? sendPort) {
    // TODO: implement onStart
    
    startSpeakTask(sendPort);
    //FlutterForegroundTask.setOnLockScreenVisibility(true);
    //startBgTts(sendPort!);
  }

  @override
  void onNotificationPressed() {
    // TODO: implement onNotificationPressed
    FlutterForegroundTask.launchApp();
  }
}
